import { computed, createApp, toRaw } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import './assets/global.css'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { useMenuStore } from "./stores/menu.js"

const app = createApp(App)

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)

app.use(ElementPlus, {
    locale: zhCn,
})

// 动态路由注册递归函数
function addDynamicRoutes(routes, parentName = 'manager') {
    routes.forEach(route => {
        router.addRoute(parentName, route)
        if (route.children && route.children.length > 0) {
            addDynamicRoutes(route.children, route.name)
        }
    })
}

// 刷新后动态路由的添加
const menuStore = useMenuStore()
const localData = localStorage.getItem('Menu')
if (localData) {
    menuStore.dynamicMenu(JSON.parse(localData).routerList)
    const routerList = computed(() => menuStore.routerList)
    addDynamicRoutes(toRaw(routerList.value))
}

// 路由守卫
router.beforeEach((to, from) => {
    const token = localStorage.getItem('pz_token');
    if (!token && to.path !== '/login') {
        return '/login';
    } else if (token && to.path === '/login') {
        return '/';
    } else {
        return true;
    }
})

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

app.use(router)
app.mount('#app')
